package com.cameron.serviceedu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cameron.serviceedu.entity.EduSubject;
import com.cameron.serviceedu.entity.dto.SubjectDto;
import com.cameron.serviceedu.entity.excel.SubjectData;
import com.cameron.serviceedu.listener.SubjectListener;
import com.cameron.serviceedu.mapper.EduSubjectMapper;
import com.cameron.serviceedu.service.EduSubjectService;
import com.cameron.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import static com.cameron.constant.CourseConstant.SUBJECT_CACHE_KEY;

/**
 * 课程科目 服务实现类
 *
 * @author cameron
 * @since 2022-06-17
 */
@Service
@Slf4j
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean saveSubject(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class, new SubjectListener(this)).sheet().doRead();
            return true;
        } catch (IOException e) {
            log.error(e.getMessage());
            return false;
        }
    }


    @SuppressWarnings("unchecked")
    @Override
    public Result getAll() {
        //从redis中获取缓存数据
        List<SubjectDto> subjectDtoList = (List<SubjectDto>) redisTemplate
                .opsForValue().get(SUBJECT_CACHE_KEY);
        //若缓存数据为空，则从数据库中查询
        if (CollectionUtils.isEmpty(subjectDtoList)) {
            LambdaQueryWrapper<EduSubject> lqw = new LambdaQueryWrapper<>();

            lqw.eq(EduSubject::getParentId, '0');

            List<EduSubject> subjectList = this.list(lqw);
            //映射为Dto
            subjectDtoList = subjectList.stream().map((item) -> {
                SubjectDto subjectDto = new SubjectDto();
                BeanUtils.copyProperties(item, subjectDto);
                LambdaQueryWrapper<EduSubject> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(EduSubject::getParentId, item.getId());
                List<EduSubject> list = this.list(wrapper);
                subjectDto.setChildren(list);
                return subjectDto;
            }).collect(Collectors.toList());
            redisTemplate.opsForValue().set(SUBJECT_CACHE_KEY, subjectDtoList);
        }
        return Result.ok().data("subList", subjectDtoList);
    }

}
